from django.contrib import admin
from .models import APIKey, ConversationSession, RateLimit

@admin.register(APIKey)
class APIKeyAdmin(admin.ModelAdmin):
    """API Key 管理界面"""
    list_display = ['key', 'user', 'created_at', 'expiry_time', 'is_valid']
    list_filter = ['created_at', 'user']
    search_fields = ['key', 'user']
    readonly_fields = ['key', 'created_at']
    ordering = ['-created_at']
    
    def is_valid(self, obj):
        """显示API Key是否有效"""
        return obj.is_valid()
    is_valid.boolean = True
    is_valid.short_description = '是否有效'

@admin.register(ConversationSession)
class ConversationSessionAdmin(admin.ModelAdmin):
    """对话会话管理界面"""
    list_display = ['session_id', 'user', 'created_at', 'updated_at', 'context_preview']
    list_filter = ['created_at', 'updated_at', 'user']
    search_fields = ['session_id', 'user__user', 'context']
    readonly_fields = ['created_at', 'updated_at']
    ordering = ['-updated_at']
    
    def context_preview(self, obj):
        """显示上下文预览"""
        if obj.context:
            return obj.context[:50] + '...' if len(obj.context) > 50 else obj.context
        return '无内容'
    context_preview.short_description = '上下文预览'

@admin.register(RateLimit)
class RateLimitAdmin(admin.ModelAdmin):
    """速率限制管理界面"""
    list_display = ['api_key', 'count', 'reset_time', 'should_limit_display']
    list_filter = ['reset_time']
    search_fields = ['api_key__key', 'api_key__user']
    readonly_fields = ['api_key']
    ordering = ['-reset_time']
    
    def should_limit_display(self, obj):
        """显示是否应该限制"""
        from django.conf import settings
        return obj.should_limit(settings.RATE_LIMIT_MAX, settings.RATE_LIMIT_INTERVAL)
    should_limit_display.boolean = True
    should_limit_display.short_description = '是否限制'

# 自定义管理后台标题
admin.site.site_header = "DeepSeek API 管理后台"
admin.site.site_title = "DeepSeek API"
admin.site.index_title = "欢迎使用 DeepSeek API 管理后台"
